<?php
namespace Admin\Controller;
use Think\Controller;
class LoginController extends Controller {
	//登陆页面
    public function index()
    {
    	//print_r($_GET);


        $this->display();
    }

    public function login()
    {
		if (IS_POST) {
			$username = I("post.username");
			$pass = I("post.pass");

	    	//检测ip 是否允许登陆的IP
	    	$ip = get_client_ip();
	    	$sql = 'select * from allow_ip_list where allow_ip='."'".$ip."'";
	    	$allow_ip = M()->query($sql);
	    	if (!$allow_ip) {
				$arr = array(
					"error" => 0,
					"info" => "当前IP已经禁止,有需要联系管理员"
					);
				echo json_encode($arr);
				exit;
	    	}
	    	//检测允许ip是否超出访问次数
	    	if ($allow_ip[0]['allow_num'] > $allow_ip[0]['allow_max']) {
				$arr = array(
					"error" => 0,
					"info" => "当前IP已超出访问次数,有需要联系管理员"
					);
				echo json_encode($arr);
				exit;
	    	}
	    	//给允许登陆ip 登陆次数加一
	    	auto_num(allow_ip_list,allow_num,$allow_ip[0]['id'],1);

			$userinfo = M('admin')->where(array('username'=>$username))->find();
			if (!$userinfo) {
				$arr = array(
					"error" => 0,
					"info" => "用户不存在"
					);
				echo json_encode($arr);
				exit;
			}
			if ($userinfo['is_denglu'] !=1) {
				$arr = array(
					"error" => 0,
					"info" => "用户已停用"
					);
				echo json_encode($arr);
				exit;
			}
			if ($userinfo['password']!=$pass) {
				$arr = array(
						"error" => 0,
						"info" => "密码输入有误"
					);
				echo json_encode($arr);
				exit;
			}

	    	//给登陆账号 登陆次数加一
	    	auto_num(admin,login_num,$userinfo['id'],1);

			//更新登陆时间,ip
			$data['login_time'] = time();
			$data['login_ip'] = get_client_ip();
			M('admin')->where(array('id'=>$userinfo["id"]))->save($data);

			//设置session登录成功
			$_SESSION["id"] = $userinfo["id"];
			$_SESSION["username"] = $userinfo["username"];

			$arr = array(
					'error' =>1,
					'info'=>"登陆中..."
					);
			echo json_encode($arr);

			}
	
    }

	//退出登录
	public function logout()
	{
		session_unset();
		session_destroy();
		$this->redirect('admin/login/index');
	}

	//无权限显示页面
	public function out()
	{
		 echo "请联系管理员开通权限";
	}




}